package com.uyayo.portal.controller;

import com.uyayo.framework.message.model.Result;
import com.uyayo.framework.common.util.CookieUtils;
import com.uyayo.framework.common.util.MD5Util;
import com.uyayo.framework.web.constants.WebConstants;
import com.uyayo.portal.biz.HomeBiz;
import com.uyayo.portal.biz.ParamBiz;
import com.uyayo.portal.shiro.MemberUsernamePasswordToken;
import com.uyayo.portal.vo.LoginVO;
import com.uyayo.system.config.service.SysParamService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 
 * Title: LoginController
 * Description:登录的Controller
 * Company: www.lelekeji.com
 *
 * @author 乐乐科技.胡逢君
 * @date 2016-4-23下午4:03:35
 * @version 1.0
 */
@Controller("memberLoginController")
@RequestMapping("/login")
public class LoginController {
	
	private final HomeBiz homeBiz;

	private final SysParamService paramsService;
	
	private final ParamBiz paramBiz;
	
	private final MessageSource messageSource;

	@Autowired
	public LoginController(HomeBiz homeBiz, SysParamService paramsService, ParamBiz paramBiz, MessageSource messageSource) {
		this.homeBiz = homeBiz;
		this.paramsService = paramsService;
		this.paramBiz = paramBiz;
		this.messageSource = messageSource;
	}

	@RequestMapping(method=RequestMethod.GET)
	public ModelAndView login(ModelAndView modelAndView,HttpServletRequest request,String redirectURL,HttpSession session) {
		String WEB_LOGIN_PAGE = paramsService.getSysParamValueByCode("WEB_LOGIN_PAGE");  	//登录页面
		String WEB_INDEX = paramsService.getSysParamValueByCode("WEB_INDEX");				//首页

		if (redirectURL == null || redirectURL.equals("")){
			
			redirectURL = WEB_INDEX;
		}
		modelAndView.addObject("redirectURL", redirectURL);
		modelAndView.setViewName(paramBiz.getWebsitTemplatesPrefix()+WEB_LOGIN_PAGE);
		return modelAndView;
	}
	
	@ResponseBody
	@RequestMapping(method=RequestMethod.POST)
	public Result login(HttpServletRequest request, HttpServletResponse response,
							   String redirectURL, @Validated LoginVO loginVO, Errors errors, HttpSession session) {
		
		String MEMBER_INDEX = paramsService.getSysParamValueByCode("MEMBER_INDEX");				//会员中心首页
		
		if (redirectURL == null || redirectURL.equals("")){
			
			redirectURL = MEMBER_INDEX;
		}
		
		if (errors.hasErrors()) {
			return new Result(400,errors.getFieldError().getDefaultMessage(),redirectURL);
	    }
		
		String captchaSession = (String) session.getAttribute(WebConstants.CAPTCHA_SESSION);

		String captcha = loginVO.getCaptcha();
		if(captcha !=null && !captcha.equals(captchaSession)){
			return new Result(400,messageSource.getMessage("captcha.error",null, request.getLocale()),redirectURL);
		}else{
			request.getSession().removeAttribute(WebConstants.CAPTCHA_SESSION);
		}
		
		String password_ = MD5Util.md5(loginVO.getPassword());
		Subject subject = SecurityUtils.getSubject();
		MemberUsernamePasswordToken token = new MemberUsernamePasswordToken(loginVO.getUsername(),password_,true,request.getLocalAddr(),captcha);
		//token.setRememberMe(true);//记住我功能
        try {
        	subject.login(token);
			return new Result(200,"登录成功！",redirectURL);
        }catch(UnknownAccountException uae){
			return new Result(400,messageSource.getMessage("loginname.password.error",null, request.getLocale()),redirectURL);
        }catch (IncorrectCredentialsException ice) {
			return new Result(400,"登录失败，请核实登录信息！",redirectURL);
        }catch (AuthenticationException e) {
            token.clear();
			return new Result(400,"认证失败，请核实登录信息！",redirectURL);
        }catch (Exception e) {
        	e.printStackTrace();
			return new Result(400,"登录失败，服务器发生异常，请管理员联系！",redirectURL);      
		}
	}
	


	/**
	 * 注销系统
	 * @param request HttpServletRequest
	 * @param response HttpServletResponse
	 * @param session HttpSession
	 * @return Result
	 */
	@ResponseBody
	@RequestMapping("logout")
	public Result logout(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		Result customResult = new Result();
		
		Subject subject = SecurityUtils.getSubject();

		
		String lOGIN_SSO = paramsService.getSysParamValueByCode("LOGIN_SSO");

		if (lOGIN_SSO.equals("1")) {
			String token = CookieUtils.getCookieValue(request, "TT_TOKEN");
			if(token==null){
				customResult.setStatus(200);
				customResult.setMessage("注销成功！");
			}else{
				//根据token换取用户信息，调用sso系统的接口。
				customResult = homeBiz.logoutUserByToken(token);
				if(customResult.getStatus()==200){
					CookieUtils.deleteCookie(request, response, "TT_TOKEN");
				}
			}
		}else{
			try {
				subject.logout();//退出登录操作
			} catch (IllegalStateException e) {
				
			}
			
			customResult.setStatus(200);
			customResult.setMessage("注销成功！");
			
		}
		return customResult;
	}
}
